Static query optimization

ABSTRACT

In some embodiments, a computer-implemented method for tuning queries for a multi-tenant database system is provided. A processor retrieves actual statistics associated with data stored on one or more servers in the multi-tenant database system. The data may be associated with one or more tenants of the multi-tenant database system. A subset of the actual statistics is selected, wherein the subset of the actual statistics is related to tenants having a data trait targeted for optimization. The processor determines synthetic statistics based on the subset of the actual statistics. An original query is received at the multi-tenant database system, wherein the original query operates upon data associated with a tenant that has the data trait targeted for optimization. The processor determines an optimal query plan based on the original query and synthetic statistics. Finally, the processor executes the original query based on the optimal query plan.

CROSS-REFERENCE TO RELATED APPLICATION

The present application claims benefit under 35 USC §119(e) of U.S.provisional Application No. 61/357,920, filed on Jun. 23, 2010, entitled“Methods and Systems for Performing Static Query Optimization in aMultitenant Environment,” the content of which is incorporated herein byreference in its entirety.

COPYRIGHT NOTICE

A portion of the disclosure of this patent document contains materialwhich is subject to copyright protection. The copyright owner has noobjection to the facsimile reproduction by anyone of the patent documentor the patent disclosure, as it appears in the Patent and TrademarkOffice patent file or records, but otherwise reserves all copyrightrights whatsoever.

BACKGROUND

The present invention generally relates to queries, and moreparticularly to query optimization in an on-demand database and/orapplication service.

Reference to the remaining portions of the specification, including thedrawings and claims, will realize other features and advantages of thepresent invention. Further features and advantages of the presentinvention, as well as the structure and operation of various embodimentsof the present invention, are described in detail below with respect tothe accompanying drawings. In the drawings, like reference numbersindicate identical or functionally similar elements.

BRIEF SUMMARY

The present invention provides systems, apparatus, and methods fortuning queries based on standardized database statistics.

In some embodiments, a computer-implemented method for tuning queriesfor a multi-tenant database system is provided. A processor retrievesactual statistics associated with data stored on one or more servers inthe multi-tenant database system. The data may be associated with one ormore tenants of the multi-tenant database system. A subset of the actualstatistics is selected, wherein the subset of the actual statistics isrelated to tenants having a data trait targeted for optimization. Theprocessor determines synthetic statistics based on the subset of theactual statistics. An original query is received at the multi-tenantdatabase system, wherein the original query operates upon dataassociated with a tenant that has the data trait targeted foroptimization. Finally, the processor determines an optimal query planbased on the original query and synthetic statistics.

In some embodiments, a tenant having a data trait targeted foroptimization has at least one of the following data traits: (1) complexdata, (2) large quantities of data, (3) a high volume of transactions,(4) a high number of transactions involving large file sizes, (5) a highnumber of resource-intensive transactions, (6) high utilization of ararely-used column or table, or (7) high utilization of a rarely-usedresource.

In some embodiments, determining the optimal query plan comprisescomputing a plurality of query plans and selecting one of the pluralityof query plans as the optimal query plan.

In some embodiments, determining synthetic statistics comprisescalculating an average value of a selected statistic in the subset ofthe actual statistics across one or more tenants having the data traittargeted for optimization. Accordingly, the optimal query plan is basedupon the average value in place of a value of the selected statistic.

In some embodiments, determining synthetic statistics comprisesdetermining the total number of tenants having the data trait targetedfor optimization. Accordingly, the optimal query plan is based upon thetotal number of tenants having the data trait targeted for optimizationin place of the total number of tenants in the multi-tenant databasesystem.

In some embodiments, determining synthetic statistics comprises settinga pre-determined value for a selected statistic in the subset of theactual statistics. Accordingly, the optimal query plan is based upon thepre-determined value in place of a value of the selected statistic.

In some embodiments, the pre-determined value for the selected statisticis based upon an exemplary tenant having the data trait targeted foroptimization. The exemplary tenant has the highest value for theselected statistic.

In some embodiments, the synthetic statistics comprise an average ofstatistical profiles for one or more tenants having the data traittargeted for optimization. A statistical profile for a tenant comprisesone or more actual statistics associated with the tenant.

In some embodiments, the synthetic statistics are uniformly configuredacross all database instances in the multi-tenant database system.

In some embodiments, a computer-implemented method for executingoptimized queries in a multi-tenant database system is provided. Anoriginal query is received at one or more servers of the multi-tenantdatabase system, wherein the original query operates upon dataassociated with a tenant that has a data trait targeted foroptimization. A processor retrieves synthetic statistics based on actualstatistics associated with one or more tenants of the multi-tenantdatabase system, wherein the one or more tenants have the data traittargeted for optimization. The processor determines an optimal queryplan based on the original query and synthetic statistics. Finally, theprocessor executes the original query based on the optimal query plan.

BRIEF DESCRIPTION OF THE DRAWINGS

In the following drawings like reference numbers are used to refer tolike elements. Although the following figures depict various examples ofthe invention, the invention is not limited to the examples depicted inthe figures.

FIG. 1 illustrates a block diagram of an environment wherein anon-demand database service might be used.

FIG. 2 illustrates a block diagram of an embodiment of elements of FIG.1 and various possible interconnections between these elements accordingto an embodiment of the present invention.

FIG. 3 is a flowchart that illustrates example processes for tuningqueries for a multi-tenant database system.

DETAILED DESCRIPTION

The present invention provides systems and methods for queryoptimization, and more particularly to systems and methods foroptimizing queries in an on-demand database and/or application service.

DEFINITIONS

Each database can generally be viewed as a collection of objects, suchas a set of logical tables, containing data fitted into predefinedcategories. A “table,” one representation of a data object, is usedherein to simplify the conceptual description of objects and customobjects in the present disclosure. It should be understood that “table”and “object” and “entity” may be used interchangeably herein. Each tablegenerally contains one or more data categories logically arranged ascolumns or fields in a viewable schema. Each row or record of a tablecontains an instance of data for each category defined by the fields.For example, a CRM database may include a table that describes acustomer with fields for basic contact information such as name,address, phone number, fax number, etc. Another table might describe apurchase order, including fields for information such as customer,product, sale price, date, etc.

As used herein, the term multi-tenant database system (“MTS”) refers tothose systems in which various elements of hardware and software of thedatabase system may be shared between one or more customers. Forexample, a given application server may simultaneously process requestsfor a great number of customers (a.k.a. tenant or organization), and agiven database table may store rows for a potentially much greaternumber of customers. In some MTS embodiments, standard entity tablesmight be provided. For CRM database applications, such standard entitiesmight include tables for relevant data, such as Account, Contact, Leadand Opportunity, each containing pre-defined fields.

As used herein, the term tenant-level statistics is broadly defined asstatistical quantities that are kept on a per-tenant basis, althoughthey may mirror the underlying relational database statistics in manyways (for example, in one aspect they track the total number of distinctvalues for indexed columns).

System Overview

FIG. 1 illustrates a block diagram of an environment 10 wherein anon-demand database service might be used. Environment 10 may includeuser systems 12, network 14, system 16, processor system 17, applicationplatform 18, network interface 20, tenant data storage 22, system datastorage 24, program code 26, and process space 28. In other embodiments,environment 10 may not have all of the components listed and/or may haveother elements instead of, or in addition to, those listed above.

Environment 10 is an environment in which an on-demand database serviceexists. User system 12 may be any machine or system that is used by auser to access a database user system. For example, any of user systems12 can be a handheld computing device, a mobile phone, a laptopcomputer, a work station, and/or a network of computing devices. Asillustrated in FIG. 1 (and in more detail in FIG. 2) user systems 12might interact via a network 14 with an on-demand database service,which is system 16.

An on-demand database service, such as system 16, is a database systemthat is made available to outside users that do not need to necessarilybe concerned with building and/or maintaining the database system, butinstead may be available for their use when the users need the databasesystem (e.g., on the demand of the users). Some on-demand databaseservices may store information from one or more tenants (i.e.,organizations) stored into tables of a common database image to form amulti-tenant database system (MTS). Accordingly, “on-demand databaseservice 16” and “system 16” will be used interchangeably herein. Adatabase image may include one or more database objects. A relationaldatabase management system (RDBMS) or the equivalent may execute storageand retrieval of information against the database object(s). Applicationplatform 18 may be a framework that allows the applications of system 16to run, such as the hardware and/or software, e.g., the operatingsystem. In an embodiment, on-demand database service 16 may include anapplication platform 18 that enables creation, managing and executingone or more applications developed by the provider of the on-demanddatabase service, users accessing the on-demand database service viauser systems 12, or third party application developers accessing theon-demand database service via user systems 12.

The users of user systems 12 may differ in their respective capacities,and the capacity of a particular user system 12 might be entirelydetermined by permissions (permission levels) for the current user. Forexample, where a salesperson is using a particular user system 12 tointeract with system 16, that user system has the capacities allotted tothat salesperson. However, while an administrator is using that usersystem to interact with system 16, that user system has the capacitiesallotted to that administrator. In systems with a hierarchical rolemodel, users at one permission level may have access to applications,data, and database information accessible by a lower permission leveluser, but may not have access to certain applications, databaseinformation, and data accessible by a user at a higher permission level.Thus, different users will have different capabilities with regard toaccessing and modifying application and database information, dependingon a user's security or permission level.

Network 14 is any network or combination of networks of devices thatcommunicate with one another. For example, network 14 can be any one orany combination of a LAN (local area network), WAN (wide area network),telephone network, wireless network, point-to-point network, starnetwork, token ring network, hub network, or other appropriateconfiguration. As the most common type of computer network in currentuse is a TCP/IP (Transfer Control Protocol and Internet Protocol)network, such as the global internetwork of networks often referred toas the “Internet” with a capital “I,” that network will be used in manyof the examples herein. However, it should be understood that thenetworks that the present invention might use are not so limited,although TCP/IP is a frequently implemented protocol.

User systems 12 might communicate with system 16 using TCP/IP and, at ahigher network level, use other common Internet protocols tocommunicate, such as HTTP, FTP, AFS, WAP, etc. In an example where HTTPis used, user system 12 might include an HTTP client commonly referredto as a “browser” for sending and receiving HTTP messages to and from anHTTP server at system 16. Such an HTTP server might be implemented asthe sole network interface between system 16 and network 14, but othertechniques might be used as well or instead. In some implementations,the interface between system 16 and network 14 includes load sharingfunctionality, such as round-robin HTTP request distributors to balanceloads and distribute incoming HTTP requests evenly over a plurality ofservers. At least as for the users that are accessing that server, eachof the plurality of servers has access to the MTS' data; however, otheralternative configurations may be used instead.

In one embodiment, system 16, shown in FIG. 1, implements a web-basedcustomer relationship management (CRM) system. For example, in oneembodiment, system 16 includes application servers configured toimplement and execute CRM software applications (application processes)as well as provide related data, code, forms, web pages and otherinformation to and from user systems 12 and to store to, and retrievefrom, a database system related data, objects, and Webpage content. Witha multi-tenant system, data for multiple tenants may be stored in thesame physical database object, however, tenant data typically isarranged so that data of one tenant is kept logically separate from thatof other tenants so that one tenant does not have access to anothertenant's data, unless such data is expressly shared. In certainembodiments, system 16 implements applications other than, or inaddition to, a CRM application. For example, system 16 may providetenant access to multiple hosted (standard and custom) applications,including a CRM application. User (or third party developer)applications, which may or may not include CRM, may be supported by theapplication platform 18, which manages creation, storage of theapplications into one or more database objects and executing of theapplications in a virtual machine in the process space of the system 16.

One arrangement for elements of system 16 is shown in FIG. 1, includinga network interface 20, application platform 18, tenant data storage 22for tenant data 23, system data storage 24 for system data 25 accessibleto system 16 and possibly multiple tenants, program code 26 forimplementing various functions of system 16, and a process space 28 forexecuting MTS system processes and tenant-specific processes, such asrunning applications as part of an application hosting service.Additional processes that may execute on system 16 include databaseindexing processes.

Several elements in the system shown in FIG. 1 include conventional,well-known elements that are explained only briefly here. For example,each user system 12 could include a desktop personal computer,workstation, laptop, PDA, cell phone, or any wireless access protocol(WAP) enabled device or any other computing device capable ofinterfacing directly or indirectly to the Internet or other networkconnection. User system 12 typically runs an HTTP client, e.g., abrowsing program, such as Microsoft's Internet Explorer browser,Netscape's Navigator browser, Opera's browser, or a WAP-enabled browserin the case of a cell phone, PDA or other wireless device, or the like,allowing a user (e.g., subscriber of the multi-tenant database system)of user system 12 to access, process and view information, pages andapplications available to it from system 16 over network 14. Each usersystem 12 also typically includes one or more user interface devices,such as a keyboard, a mouse, trackball, touch pad, touch screen, pen orthe like, for interacting with a graphical user interface (GUI) providedby the browser on a display (e.g., a monitor screen, LCD display, etc.)in conjunction with pages, forms, applications and other informationprovided by system 16 or other systems or servers. For example, the userinterface device can be used to access data and applications hosted bysystem 16, and to perform searches on stored data, and otherwise allow auser to interact with various GUI pages that may be presented to a user.As discussed above, embodiments are suitable for use with the Internet,which refers to a specific global internetwork of networks. However, itshould be understood that other networks can be used instead of theInternet, such as an intranet, an extranet, a virtual private network(VPN), a non-TCP/IP based network, any LAN or WAN or the like.

According to one embodiment, each user system 12 and all of itscomponents are operator configurable using applications, such as abrowser, including computer code run using a central processing unitsuch as an Intel Pentium® processor or the like. Similarly, system 16(and additional instances of an MTS, where more than one is present) andall of their components might be operator configurable usingapplication(s) including computer code to run using a central processingunit such as processor system 17, which may include an Intel Pentium®processor or the like, and/or multiple processor units. A computerprogram product embodiment includes a machine-readable storage medium(media) having instructions stored thereon/in which can be used toprogram a computer to perform any of the processes of the embodimentsdescribed herein. Computer code for operating and configuring system 16to intercommunicate and to process web pages, applications and otherdata and media content as described herein are preferably downloaded andstored on a hard disk, but the entire program code, or portions thereof,may also be stored in any other volatile or non-volatile memory mediumor device as is well known, such as a ROM or RAM, or provided on anymedia capable of storing program code, such as any type of rotatingmedia including floppy disks, optical discs, digital versatile disk(DVD), compact disk (CD), microdrive, and magneto-optical disks, andmagnetic or optical cards, nanosystems (including molecular memory ICs),or any type of media or device suitable for storing instructions and/ordata. Additionally, the entire program code, or portions thereof, may betransmitted and downloaded from a software source over a transmissionmedium, e.g., over the Internet, or from another server, as is wellknown, or transmitted over any other conventional network connection asis well known (e.g., extranet, VPN, LAN, etc.) using any communicationmedium and protocols (e.g., TCP/IP, HTTP, HTTPS, Ethernet, etc.) as arewell known. It will also be appreciated that computer code forimplementing embodiments of the present invention can be implemented inany programming language that can be executed on a client system and/orserver or server system such as, for example, C, C++, HTML, any othermarkup language, Java™, JavaScript, ActiveX, any other scriptinglanguage, such as VBScript, and many other programming languages as arewell known may be used. (Java™ is a trademark of Sun Microsystems,Inc.).

According to one embodiment, each system 16 is configured to provide webpages, forms, applications, data and media content to user (client)systems 12 to support the access by user systems 12 as tenants of system16. As such, system 16 provides security mechanisms to keep eachtenant's data separate unless the data is shared. If more than one MTSis used, they may be located in close proximity to one another (e.g., ina server farm located in a single building or campus), or they may bedistributed at locations remote from one another (e.g., one or moreservers located in city A and one or more servers located in city B). Asused herein, each MTS could include one or more logically and/orphysically connected servers distributed locally or across one or moregeographic locations. Additionally, the term “server” is meant toinclude a computer system, including processing hardware and processspace(s), and an associated storage system and database application(e.g., OODBMS or RDBMS) as is well known in the art. It should also beunderstood that “server system” and “server” are often usedinterchangeably herein. Similarly, the database object described hereincan be implemented as single databases, a distributed database, acollection of distributed databases, a database with redundant online oroffline backups or other redundancies, etc., and might include adistributed database or storage network and associated processingintelligence.

FIG. 2 also illustrates environment 10. However, in FIG. 2, elements ofsystem 16 and various interconnections in an embodiment are furtherillustrated. FIG. 2 shows that user system 12 may include processorsystem 12A, memory system 12B, input system 12C, and output system 12D.FIG. 2 shows network 14 and system 16. FIG. 2 also shows that system 16may include tenant data storage 22, tenant data 23, system data storage24, system data 25, User Interface (UI) 30, Application ProgramInterface (API) 32, PL/SOQL 34, save routines 36, application setupmechanism 38, applications servers 100 ₁-100 _(N), system process space102, tenant process spaces 104, tenant management process space 110,tenant storage area 112, user storage 114, and application metadata 116.In other embodiments, environment 10 may not have the same elements asthose listed above and/or may have other elements instead of, or inaddition to, those listed above.

User system 12, network 14, system 16, tenant data storage 22, andsystem data storage 24 were discussed above in FIG. 1. Regarding usersystem 12, processor system 12A may be any combination of one or moreprocessors. Memory system 12B may be any combination of one or morememory devices, short term, and/or long term memory. Input system 12Cmay be any combination of input devices, such as one or more keyboards,mice, trackballs, scanners, cameras, and/or interfaces to networks.Output system 12D may be any combination of output devices, such as oneor more monitors, printers, and/or interfaces to networks. As shown byFIG. 2, system 16 may include a network interface 20 (of FIG. 1)implemented as a set of HTTP application servers 100, an applicationplatform 18, tenant data storage 22, and system data storage 24. Alsoshown is system process space 102, including individual tenant processspaces 104 and a tenant management process space 110. Each applicationserver 100 may be configured to tenant data storage 22 and the tenantdata 23 therein, and system data storage 24 and the system data 25therein to serve requests of user systems 12. The tenant data 23 mightbe divided into individual tenant storage areas 112, which can be eithera physical arrangement and/or a logical arrangement of data. Within eachtenant storage area 112, user storage 114 and application metadata 116might be similarly allocated for each user. For example, a copy of auser's most recently used (MRU) items might be stored to user storage114. Similarly, a copy of MRU items for an entire organization that is atenant might be stored to tenant storage area 112. A UI 30 provides auser interface and an API 32 provides an application programmerinterface to system 16 resident processes to users and/or developers atuser systems 12. The tenant data and the system data may be stored invarious databases, such as one or more Oracle™ databases.

Application platform 18 includes an application setup mechanism 38 thatsupports application developers' creation and management ofapplications, which may be saved as metadata into tenant data storage 22by save routines 36 for execution by subscribers as one or more tenantprocess spaces 104 managed by tenant management process 110 for example.Invocations to such applications may be coded using PL/SOQL 34 thatprovides a programming language style interface extension to API 32. Adetailed description of some PL/SOQL language embodiments is discussedin commonly owned U.S. Pat. No. 7,730,478 entitled, METHOD AND SYSTEMFOR ALLOWING ACCESS TO DEVELOPED APPLICATIONS VIA A MULTI-TENANTON-DEMAND DATABASE SERVICE, by Craig Weissman, filed Sep. 21, 2007,which is incorporated in its entirety herein for all purposes.Invocations to applications may be detected by one or more systemprocesses, which manages retrieving application metadata 116 for thesubscriber making the invocation and executing the metadata as anapplication in a virtual machine.

Each application server 100 may be communicably coupled to databasesystems, e.g., having access to system data 25 and tenant data 23, via adifferent network connection. For example, one application server 100 ₁might be coupled via the network 14 (e.g., the Internet), anotherapplication server 100 _(N-1) might be coupled via a direct networklink, and another application server 100 _(N) might be coupled by yet adifferent network connection. Transfer Control Protocol and InternetProtocol (TCP/IP) are typical protocols for communicating betweenapplication servers 100 and the database system. However, it will beapparent to one skilled in the art that other transport protocols may beused to optimize the system depending on the network interconnect used.

In certain embodiments, each application server 100 is configured tohandle requests for any user associated with any organization that is atenant. Because it is desirable to be able to add and remove applicationservers from the server pool at any time for any reason, there ispreferably no server affinity for a user and/or organization to aspecific application server 100. In one embodiment, therefore, aninterface system implementing a load balancing function (e.g., an F5Big-IP load balancer) is communicably coupled between the applicationservers 100 and the user systems 12 to distribute requests to theapplication servers 100. In one embodiment, the load balancer uses aleast connections algorithm to route user requests to the applicationservers 100. Other examples of load balancing algorithms, such as roundrobin and observed response time, also can be used. For example, incertain embodiments, three consecutive requests from the same user couldhit three different application servers 100, and three requests fromdifferent users could hit the same application server 100. In thismanner, system 16 is multi-tenant, wherein system 16 handles storage of,and access to, different objects, data and applications across disparateusers and organizations.

As an example of storage, one tenant might be a company that employs asales force where each salesperson uses system 16 to manage their salesprocess. Thus, a user might maintain contact data, leads data, customerfollow-up data, performance data, goals and progress data, etc., allapplicable to that user's personal sales process (e.g., in tenant datastorage 22). In an example of a MTS arrangement, since all of the dataand the applications to access, view, modify, report, transmit,calculate, etc., can be maintained and accessed by a user system havingnothing more than network access, the user can manage his or her salesefforts and cycles from any of many different user systems. For example,if a salesperson is visiting a customer and the customer has Internetaccess in their lobby, the salesperson can obtain critical updates as tothat customer while waiting for the customer to arrive in the lobby.

While each user's data might be separate from other users' dataregardless of the employers of each user, some data might beorganization-wide data shared or accessible by a plurality of users orall of the users for a given organization that is a tenant. Thus, theremight be some data structures managed by system 16 that are allocated atthe tenant level while other data structures might be managed at theuser level. Because an MTS might support multiple tenants includingpossible competitors, the MTS should have security protocols that keepdata, applications, and application use separate. Also, because manytenants may opt for access to an MTS rather than maintain their ownsystem, redundancy, up-time, and backup are additional functions thatmay be implemented in the MTS. In addition to user-specific data andtenant-specific data, system 16 might also maintain system level datausable by multiple tenants or other data. Such system level data mightinclude industry reports, news, postings, and the like that are sharableamong tenants.

In certain embodiments, user systems 12 (which may be client systems)communicate with application servers 100 to request and updatesystem-level and tenant-level data from system 16 that may requiresending one or more queries to tenant data storage 22 and/or system datastorage 24. System 16 (e.g., an application server 100 in system 16)automatically generates one or more SQL statements (e.g., one or moreSQL queries) that are designed to access the desired information. Systemdata storage 24 may generate query plans to access the requested datafrom the database.

A table generally contains one or more data categories logicallyarranged as columns or fields in a viewable schema. Each row or recordof a table contains an instance of data for each category defined by thefields. For example, a CRM database may include a table that describes acustomer with fields for basic contact information such as name,address, phone number, fax number, etc. Another table might describe apurchase order, including fields for information such as customer,product, sale price, date, etc. Yet another table or object mightdescribe an Opportunity, including fields such as organization, period,forecast type, user, territory, etc.

In some multi-tenant database systems, tenants may be allowed to createand store custom objects, or they may be allowed to customize standardentities or objects, for example by creating custom fields for standardobjects, including custom index fields. U.S. Pat. No. 7,779,039,entitled “Custom Entities and Fields in a Multi-Tenant Database System”,by Craig Weissman, filed Apr. 2, 2004, which is hereby incorporatedherein by reference, teaches systems and methods for creating customobjects as well as customizing standard objects in a multi-tenantdatabase system.

Query Tuning

In a typical multi-tenant environment, using actual database statisticsto generate query plans may lead to poor efficiency because of theschema of a multi-tenant database system—data related to multipletenants may be stored together in a single table although most datatransactions are tenant-specific. Typical database statistics from aglobal perspective may tend to reflect the average or typicalorganization (which may be small and have a simple dataset).Unfortunately, actual database statistics often may not accuratelycharacterize certain organizations (typically, the largest ones) withunique data traits (which are typically difficult to optimize), sincethese are typically few in number. Such unique data traits may include,for example: (1) complex data, (2) large quantities of data, (3) a highvolume of transactions, (4) a high number of transactions involvinglarge file sizes, (5) a high number of resource-intensive transactions(a “resource” may include any typical resource associated with adatabase server, e.g., memory, CPU, network bandwidth, etc.), or (6) ahigh level of utilization of a resource that is rarely used by mosttenants. In addition, certain columns and tables that are accessible toall tenants, but only utilized by a few tenants, may have distributionsshowing few populated rows or a lot of null values, which tends to throwoff query plans for those few tenants that actually utilize thosetables/columns. Embodiments are disclosed herein in order to establishsynthetic database statistics to be used in facilitating optimized queryplans for tenants having a data trait targeted for optimization.

FIG. 3 is a flowchart that illustrates example processes for tuningqueries for a multi-tenant database system. In some embodiments, theprocesses may be performed by one or more servers in the multi-tenantdatabase system; in other embodiments, the processes may be performed bya separate computer, or by a combination of computers outside of andwithin the multi-tenant database system. The processes shown in FIG. 3are described below in conjunction with an example use case toillustrate the steps in further detail. The example is provided purelyfor illustrative purposes and is not intended to limit the scope of theinvention in any way. The example is based on a multi-tenant databasesystem where each tenant typically only has access to data associatedwith their own tenant_id. In the example, a table cases and a tablecomments in the multi-tenant database system are used in conjunctionwith application features of the multi-tenant database system thatprovide for creation and tracking of customer support issues (tablecases includes data for each customer-submitted support issue, and tablecomments includes data for comments entered by customer supportrepresentatives regarding each customer-submitted support issue).

Table cases includes columns tenant_id, cases_id, subject, etc. Indexeson table cases include: PKCases (tenant_id, cases_id).

Table comments includes columns tenant_id, comments_id, cases_id,comments_text, created_date, etc. Indexes on table comments include:PKComments (tenant_id, comments_id), FKComments_Cases (tenant_id,cases_id), IEComments_Created (tenant_id, created_date).

In step 310, conventional (actual) statistical data is retrieved. Thestatistical data may include statistics regarding (1) data stored in themulti-tenant database system, wherein the data is associated with one ormore tenants of the multi-tenant database system; (2) transactionsinvolving the multi-tenant database system; or (3) administrative dataand/or operations related to the multi-tenant database system. In theexample use case, the conventional statistical data indicates:

Table cases: 10 million rows. Column tenant_id: 10,000 distinct values.

Table comments: 30 million rows. Column tenant_id: 10,000 distinctvalues; column cases_id: 10,000,000 distinct values; columncreated_date: 4,000 distinct values.

In step 320, a subset of the statistical data is selected. This subsetof statistical data includes statistical data related to some or alltenants having one or more data traits targeted for optimization. In ourexample use case, the data trait targeted for optimization is, at a highlevel, whether or not the tenant utilizes table cases; “utilization” oftable cases is indicated when more than one row in table cases existsfor any given tenant. Therefore, the subset of statistical data shouldinclude all distinct tenant_id foreign keys for which two or more rowsexist in table cases.

In step 330, synthetic statistics are calculated based on the subset ofstatistical data. In some embodiments, the synthetic statistics may bederived from the subset of statistical data by modifying one or moreaspects of the data, and then re-calculating the statistical data. Inour example use case, calculation of the relevant synthetic statistic(i.e., the number of distinct tenant_id foreign keys in the subset ofstatistical data related to tenants who utilize features using tablecases) indicates that there are actually only 500 distinct tenant_idforeign keys for which two or more rows exist in table cases (a smallnumber when compared to the total number of distinct tenant_id foreignkeys in table cases: 10,000).

Table cases: 10 million rows. Column tenant_id: 500 distinct values.

Table comments: 30 million rows. Column tenant_id: 500 distinct values;column cases_id: 10,000,000 distinct values; column created_date: 4,000distinct values.

In step 340, an original query is received at the multi-tenant databasesystem, wherein the original query accesses data associated with aparticular tenant that has at least one of the one or more data traitstargeted for optimization. In our example use case, given the followingquery:

SELECT comments_id, comments_text

FROM comments

WHERE tenant_id=:1

AND cases_id IN (:2, :3, :4)

AND created_date=:5

a conventional query optimization methodology may result in these twoquery plan options:

Query Plan 1

OPERATION OBJECT ROWS COST TABLE ACCESS COMMENTS 1 4 INDEX RANGEIECOMMENTS_CREATED 1 3 SCANQuery Plan 2

OPERATION OBJECT ROWS COST TABLE ACCESS COMMENTS 1 9 INDEX RANGEPKCOMMENTS 3 6 SCANThe statistics tell the database that on the average, for a giventenant_id and created_date, there are very few rows (it will calculate avalue of 1 row—30 million rows/10000 tenants/4000 distinct dates). Forthe average tenant, Query Plan 1 appears to be less costly than QueryPlan 2 and may suffice. However, most queries to tables cases andcomments will originate from tenants who utilize these tables morefully; these tenants may have many customer support issues submitted ina single day. For these tenants, Query Plan 1 may perform quite poorlyif many comments fall into the given date range, since the databasewould have to look each row up in the table before applying the primarykey filter (on tenant_id).

In step 350, an improved query is generated based on the original queryand the synthetic statistics. In one embodiment, a synthetic statisticderived from the actual statistic is based upon an analysis of theactual distribution of distinct values for the foreign key. In ourexample use case, the same optimization methodology, based upon thesynthetic statistic instead of the actual statistic, may result in adifferent set of query plan options:

Query Plan 1

OPERATION OBJECT ROWS COST TABLE ACCESS COMMENTS 1 18 INDEX RANGEIECOMMENTS_CREATED 15 3 SCANQuery Plan 2

OPERATION OBJECT ROWS COST TABLE ACCESS COMMENTS 1 9 INDEX RANGEPKCOMMENTS 3 6 SCANIncorporation of the synthetic statistic causes the computed cost forthe Query Plan 1 (i.e., the IECOMMENTS_CREATED plan) to changesignificantly, whereas the cost of Query Plan 2 (i.e., the PKCOMMENTSquery plan) to remain the same. Since the total usage of the table isdominated by no more than 500 tenants (since the likelihood that anygiven query on tables cases and/or comments was submitted by one ofthose 500 tenants), Query Plan 2 is ultimately selected as the moreoptimal query plan.

In some embodiments, the same table, index, and column statistics aresynthetically standardized across all database instances, regardless ofthe actual differences in data distribution across databases, and nopartition-level statistics are set within a database. The reason forthis is that it is desirable to have consistent query plans acrossdatabase instances, in order to minimize management overhead.Furthermore, while the optimum query plan for a query depends on thelocal data distribution, in a multi-tenant database system, the relevantlocal data distribution is the distribution for the given organization(i.e., tenant), not the database. The query plan for one organizationshould not depend on what other customers happen to be on the samedatabase, which is what one would get if statistics were conventionallygathered on each database.

In some embodiments, synthetic statistics are scaled in order to makethem representative of the data distributions of the largestorganizations in the system, rather than the average organizations.Conventional database statistics would indicate that the typicalcustomer has relatively few rows, or tends to have a null value in oneor more columns (because there may be a small number of very largeorganizations compared to a very large number of small and trialorganizations). However, the large organizations producedisproportionately more load than the small organizations, since theyhave more users running queries and their queries run against muchlarger data sets. Also, the database will perform far too many largedata scans if the statistics indicate that the average organization sizeis small, since the relative cost of nested loop joins to large scans ishigher. Therefore, it is desirable for the system to perform well forthe very large organizations. To accomplish this, as in the example usecase above, the distinct value counts for certain key columns are set toartificially low values. For example, the database may be told thatthere are only 1000 distinct tenant_id's in a table when the true numberis more like 50,000.

In some embodiments, certain columns tend to have a very small number ofdistinct values within a typical organization but many distinct valuesacross all organizations. For these columns, the synthetic statisticsare set with the number of distinct values for a typical organization.This informs the database that a filter on this column is not veryselective (whereas with conventional statistics it would compute thatthe filter is quite selective.) An example of such a column would be arecord_type_id; customers can define record types to classify rows of anentity into different types. A given organization might have on theorder of 5 or 10 record types, but the record type ids are distinctacross all organizations, so the table might have 50,000 distinctvalues. If a query filters on record_type_id, it is desirable that thedatabase to compute that that filter will reduce the rowcount byapproximately a factor of 5, not 50,000.

In some embodiments, a database administrator or other user of themulti-tenant database system may manually configure the syntheticstatistics to more closely tailor database performance in accordancewith perceived or anticipated needs.

While the invention has been described by way of example and in terms ofthe specific embodiments, it is to be understood that the invention isnot limited to the disclosed embodiments. To the contrary, it isintended to cover various modifications and similar arrangements aswould be apparent to those skilled in the art. Therefore, the scope ofthe appended claims should be accorded the broadest interpretation so asto encompass all such modifications and similar arrangements.

What is claimed is:
 1. A computer-implemented method for tuning queriesfor a multi-tenant database system, the method comprising: retrievingactual statistics associated with data stored on one or more servers inthe multi-tenant database system, wherein the data is associated withone or more tenants of the multi-tenant database system; selecting asubset of the actual statistics, wherein the subset of the actualstatistics is related to tenants having a data trait targeted foroptimization, wherein a tenant having a data trait targeted foroptimization has at least one of the following data traits: (1) a highvolume of transactions, (2) a high number of transactions involvinglarge file sizes, (3) a high number of resource-intensive transactions,(4) high utilization of a rarely-used column or table, or (5) highutilization of a rarely-used resource; determining, using one or moreprocessors associated with the one or more servers, synthetic statisticsbased on the subset of the actual statistics, wherein the syntheticstatistics are derived from the subset of actual statistics by modifyingone or more aspects of the data based on a subset of the tenants of themulti-tenant database system, the subset of tenants having the datatrait targeted for optimization, and then re-calculating statisticaldata to generate the synthetic statistics; receiving an original querytransmitted to the multi-tenant database system by a user associatedwith a tenant that has the data trait targeted for optimization, whereinthe original query operates upon data associated with the tenant; anddetermining, using the processor, an optimal query plan based on theoriginal query and the synthetic statistics.
 2. The method of claim 1,wherein determining the optimal query plan comprises: computing, usingthe one or more processors, a plurality of query plans; and selectingthe optimal query plan from the plurality of query plans.
 3. The methodof claim 1, wherein determining synthetic statistics comprisescalculating an average value of a selected statistic in the subset ofthe actual statistics across one or more tenants having the data traittargeted for optimization; and wherein the optimal query plan is basedupon the average value in place of a value of the selected statistic. 4.The method of claim 1, wherein determining synthetic statisticscomprises determining the total number of tenants having the data traittargeted for optimization; and wherein the optimal query plan is basedupon the total number of tenants having the data trait targeted foroptimization in place of the total number of tenants in the multi-tenantdatabase system.
 5. The method of claim 1, wherein determining syntheticstatistics comprises setting a pre-determined value for a selectedstatistic in the subset of the actual statistics; and wherein theoptimal query plan is based upon the pre-determined value in place of avalue of the selected statistic.
 6. The method of claim 5, wherein thepre-determined value for the selected statistic is based upon anexemplary tenant having the data trait targeted for optimization, andwherein the exemplary tenant has the highest value for the selectedstatistic.
 7. The method of claim 1, wherein the synthetic statisticscomprise an average of statistical profiles for one or more tenantshaving the data trait targeted for optimization, and wherein astatistical profile for a tenant comprises one or more actual statisticsassociated with the tenant.
 8. A computer-implemented method forexecuting optimized queries in a multi-tenant database system, themethod comprising: receiving an original query transmitted to one ormore servers of the multi-tenant database system, wherein the originalquery operates upon data associated with a tenant of a plurality oftenants of the multi-tenant database system, wherein the tenant has adata trait targeted for optimization; retrieving synthetic statistics,wherein the synthetic statistics are based on actual statisticsassociated with one or more tenants of the multi-tenant database system,and wherein the one or more tenants have the data trait targeted foroptimization, wherein a tenant having a data trait targeted foroptimization has at least one of the following data traits: (1) a highvolume of transactions, (2) a high number of transactions involvinglarge file sizes, (3) a high number of resource-intensive transactions,(4) high utilization of a rarely-used column or table, or (5) highutilization of a rarely-used resource; determining, using one or moreprocessors associated with the one or more servers, synthetic statisticsbased on the subset of the actual statistics, wherein the syntheticstatistics are derived from the subset of actual statistics by modifyingone or more aspects of the data, and then re-calculating statisticaldata to generate the synthetic statistics based on a subset of thetenants of the multi-tenant database system, the subset of tenantshaving the data trait targeted for optimization; executing, using theone or more processors, an optimal query plan based on the syntheticstatistics.
 9. The method of claim 8, wherein the synthetic statisticsare uniformly configured across all database instances in themulti-tenant database system.
 10. The method of claim 8, whereindetermining the optimal query plan comprises: computing, using the oneor more processors, a plurality of query plans; and selecting theoptimal query plan from the plurality of query plans; and whereinexecuting the original query based on the query plan comprises executingthe original query based on the optimal query plan.
 11. The method ofclaim 8, wherein the synthetic statistics comprise an average value of aselected statistic in the subset of the actual statistics across one ormore tenants having the data trait targeted for optimization; andwherein the optimal query plan is based upon the average value in placeof a value of the selected statistic.
 12. The method of claim 8, whereinthe synthetic statistics comprise the total number of tenants having thedata trait targeted for optimization; and wherein the optimal query planis based upon the total number of tenants having the data trait targetedfor optimization in place of the total number of tenants in themulti-tenant database system.
 13. The method of claim 8, wherein thesynthetic statistics comprise a pre-determined value for a selectedstatistic in the subset of the actual statistics; and wherein theoptimal query plan is based upon the pre-determined value in place of avalue of the selected statistic.
 14. The method of claim 13, wherein thepre-determined value for the selected statistic is based upon anexemplary tenant having the data trait targeted for optimization, andwherein the exemplary tenant has the highest value for the selectedstatistic.
 15. The method of claim 13, wherein the pre-determined valuefor the selected statistic is based upon manually-configured settings.16. The method of claim 8, wherein the synthetic statistics comprise anaverage of statistical profiles for one or more tenants having the datatrait targeted for optimization, and wherein a statistical profile for atenant comprises one or more actual statistics associated with thetenant.
 17. A non-transitory computer-readable medium containing programcode executable by a processor in a computer to tune a query, theprogram code including instructions to: retrieve actual statisticsassociated with data stored on one or more servers in the multi-tenantdatabase system, wherein the data is associated with one or more tenantsof the multi-tenant database system; select a subset of the actualstatistics, wherein the subset of the actual statistics is related totenants having a data trait targeted for optimization, wherein a tenanthaving a data trait targeted for optimization has at least one of thefollowing data traits: (1) a high volume of transactions, (2) a highnumber of transactions involving large file sizes, (3) a high number ofresource-intensive transactions, (4) high utilization of a rarely-usedcolumn or table, or (5) high utilization of a rarely-used resource;determine, using one or more processors associated with the one or moreservers, synthetic statistics based on the subset of the actualstatistics, wherein the synthetic statistics are derived from the subsetof actual statistics by modifying one or more aspects of the data, andthen re-calculating statistical data to generate the syntheticstatistics based on a subset of the tenants of the multi-tenant databasesystem, the subset of tenants having the data trait targeted foroptimization; receive an original query transmitted to the multi-tenantdatabase system by a user associated with a tenant that has the datatrait targeted for optimization, wherein the original query operatesupon data associated with the tenant; and generate, using the processor,an optimal query plan based on the original query and the syntheticstatistics.
 18. A system comprising: one or more processors; and amemory encoded with instructions to configure the one or more processorsto: retrieve actual statistics associated with data stored on one ormore servers in the multi-tenant database system, wherein the data isassociated with one or more tenants of the multi-tenant database system;select a subset of the actual statistics, wherein the subset of theactual statistics is related to tenants having a data trait targeted foroptimization, wherein a tenant having a data trait targeted foroptimization has at least one of the following data traits: (1) a highvolume of transactions, (2) a high number of transactions involvinglarge file sizes, (3) a high number of resource-intensive transactions,(4) high utilization of a rarely-used column or table, or (5) highutilization of a rarely-used resource; determine, using one or moreprocessors associated with the one or more servers, synthetic statisticsbased on the subset of the actual statistics, wherein the syntheticstatistics are derived from the subset of actual statistics by modifyingone or more aspects of the data, and then re-calculating statisticaldata to generate the synthetic statistics based on a subset of thetenants of the multi-tenant database system, the subset of tenantshaving the data trait targeted for optimization; receive an originalquery transmitted to the multi-tenant database system by a userassociated with a tenant that has the data trait targeted foroptimization, wherein the original query operates upon data associatedwith the tenant; generate, using the processor, an optimal query planbased on the original query and the synthetic statistics; and executethe original query based on the optimal query plan.
 19. The system ofclaim 18, wherein the synthetic statistics are uniformly configuredacross all database instances in the multi-tenant database system.